#include "config.h"

#include "ms2wgen.h"

static ecm_time_t	timecur;
static msl_arrival_t	msl_arrival;

static void
create_log(FILE *fp, const char *datetime_str, wg_session_t *session)
{
	wg_access_t	*access;

	///TODO
	access = get_head_access(session);
	ecm_fprintf(fp, "%s media%u %u %u 1 200 %u %u %u\n",
		    datetime_str,
		    session->mid,
		    access->startstamp, access->endstamp - access->startstamp + 1,
		    session->sid,
		    media_length, media_size);
}

static void
create_wg_session(ecm_uint32 tick, ecm_uint32 n_arrivals)
{
	ecm_uint32	i;

	for (i = 0; i < n_arrivals; i++) {
		add_wg_session(tick);
	}
}

static void
build_logs(FILE *fp)
{
	wg_session_t	*session;
	struct tm	tm;
	ecm_uint32	i;

	for (i = 0; i < duration; i++) {
		char	*datetime_str;
		int n_arrivals;

		datetime_str = ecm_strftime("%Y-%m-%d %H:%M:%S", ecm_localtime(&timecur, &tm));
		n_arrivals = msl_arrival_get(msl_arrival);
		create_wg_session(i, n_arrivals);

		while ((session = get_wg_session(i))) {
			create_log(fp, datetime_str, session);
			put_wg_session(session);
		}
		ecm_free(datetime_str);
		timecur++;
	}
}

void
gen_logs(void)
{
	FILE	*fp;

	if (ecm_empty_str(output)) {
		fp = ecm_stdout;
	}
	else {
		fp = ecm_fopen(output, "a+");
		if (fp == NULL) {
			ERR("%s: cannot create", output);
			return;
		}
	}

	timecur = ecm_time();
	msl_arrival = msl_arrival_create(arrival_lambda, 0);

	build_logs(fp);

	if (fp != ecm_stdout)
		ecm_fclose(fp);
}
